package com.example.canvasdemo.network

import android.util.Log
import okhttp3.*
import java.util.concurrent.TimeUnit

class WebSocketClient {

    private var webSocket: WebSocket? = null
    private val client: OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时时间
        .writeTimeout(30, TimeUnit.SECONDS)  // 写入超时时间
        .readTimeout(30, TimeUnit.SECONDS)  // 读取超时时间
        .build()

    // 初始化 WebSocket 连接
    fun connectToServer(url: String, roomId: Long, userId: Long) {
        val request = Request.Builder().url(url).build()

        // 创建 WebSocket，并监听消息
        webSocket = client.newWebSocket(request, object : WebSocketListener() {
            override fun onOpen(webSocket: WebSocket, response: Response) {
                super.onOpen(webSocket, response)
                Log.d("WebSocket", "连接已建立")
                // 发送连接成功后的初始化消息，如用户信息、房间 ID 等
                val connectMessage = "{\"roomId\": $roomId, \"userId\": $userId}"
                webSocket.send(connectMessage)
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                super.onMessage(webSocket, text)
                Log.d("WebSocket", "接收到消息: $text")
                // 在此处理接收到的消息
                // 例如通过接口通知界面更新 UI
                onMessageReceived(text)
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                super.onFailure(webSocket, t, response)
                Log.e("WebSocket", "连接失败: ${t.message}")
            }

            override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosing(webSocket, code, reason)
                Log.d("WebSocket", "连接关闭: $reason")
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosed(webSocket, code, reason)
                Log.d("WebSocket", "连接已关闭")
            }
        })
    }

    // 发送消息到服务器
    fun sendMessage(message: String) {
        webSocket?.send(message)
    }

    // 关闭 WebSocket 连接
    fun closeConnection() {
        webSocket?.close(1000, "Goodbye")  // 1000 是正常关闭的状态码
    }

    // 接收到消息后的处理
    private fun onMessageReceived(message: String) {
        // 在此将接收到的消息传递给 UI 层，更新聊天界面
        // 你可以使用 LiveData 或其他方式更新界面
    }
}
